package com.jd.org.service.impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.utils.MD5Utils;
import com.jd.basic.utils.StrUtils;
import com.jd.org.domain.Employee;
import com.jd.org.mapper.EmployeeMapper;
import com.jd.org.service.EmployeeService;
import com.jd.system.mapper.RoleMapper;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 小林同学
 * @version 1.0
 * @description: TODO
 * @date 2023/2/18 20:51
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RoleMapper roleMapper;
    @Override
    public List<Employee> getEmpByDeptId(Long id) {
        return employeeMapper.getEmpByDeptId(id);
    }

    @Override
    public Employee findByLogininfoId(Long logininfoId) {
        return employeeMapper.findByLogininfoId(logininfoId);
    }

    @Override
    public List<Employee> getEmployees(Long shopId) {
        return employeeMapper.getEmployees(shopId);
    }

    @Override
    public void add(Employee employee) {
        // 加盐值
        this.setSalt(employee);
        // 赋值给logininfo
        Logininfo logininfo = employee.getLogininfo(employee);

        logininfoMapper.add(logininfo);

        Long logininfoId = logininfo.getId();

        employee.setLogininfoId(logininfoId);

        employeeMapper.add(employee);

        // 添加员工时，同时添加到员工-角色表
        if (null != employee.getRoles()) {
            roleMapper.addMiddle(employee.getId(), employee.getRoles());
        }
    }

    @Override
    public void delete (Long id){
        // 通过id获取对象，从而找到对应的logininfoId
        Employee employee = employeeMapper.findById(id);
        Long logininfoId = employee.getLogininfoId();
        // 先删除employee表中的数据
        employeeMapper.delete(id);
        // 在通过logininfoId在logininfo表中删除对应的对象
        logininfoMapper.delete(logininfoId);
        // 删除员工时，同时删除到员工-角色表
        roleMapper.deleteByEmpId(id);
    }

    @Override
    public void update(Employee employee){
        // 创建一个对象
        Logininfo logininfo = employee.getLogininfo(employee);
        logininfo.setId(employee.getLogininfoId());
        logininfo.setDisable(true);
        logininfoMapper.update(logininfo);
        // 修改员工时，先删除到员工-角色表，再添加到员工-角色表
        roleMapper.deleteByEmpId(employee.getId());
        roleMapper.addMiddle(employee.getId(), employee.getRoles());
    }

    private void setSalt(Employee employee){
        //盐值
        String salt = StrUtils.getComplexRandomString(32);
        employee.setSalt(salt);
        /// 加密密码
        String pw = MD5Utils.encrypByMd5(salt + employee.getPassword());
        employee.setPassword(pw);
    }


}
